package com.zhx.factory.support;

import cn.hutool.core.bean.BeanUtil;
import com.zhx.PropertyValue;
import com.zhx.PropertyValues;
import com.zhx.factory.BeansException;
import com.zhx.factory.config.BeanDefinition;
import com.zhx.factory.config.BeanReference;

import java.lang.reflect.Constructor;

/**
 * @author zhx
 * @title  实例化bean，并存入缓存
 * @description
 * @date 2022/9/29 11:15
 */
public abstract class AbstractAutowireCapableBeanFactory extends AbstractBeanFactory{

    /**
     * 使用Cglib生成实例
     */
    //private InstantiationStrategy instantiationStrategy = new CglibSubclassingInstantiationStrategy();
    private InstantiationStrategy instantiationStrategy = new SimpleInstantiationStrategy();

    /**
     * 有参构造方法创建实例
     * @param beanName
     * @param beanDefinition
     * @return
     * @throws BeansException
     */
    @Override
    protected Object createBean(String beanName, BeanDefinition beanDefinition,Object[] args) throws BeansException {
        Object bean = null;
        try {
            //初始化bean
            bean = createBeanInstance(beanDefinition, beanName, args);

            //填充属性
            applyPropertyValues(beanName,bean,beanDefinition);

        } catch (Exception e) {
            throw new BeansException("Instantiation of bean failed", e);
        }

        addSingleton(beanName, bean);
        return bean;
    }

    protected void applyPropertyValues(String beanName, Object bean, BeanDefinition beanDefinition){
        try{
            PropertyValues propertyValues = beanDefinition.getPropertyValues();
            for (PropertyValue propertyValue : propertyValues.getPropertyValues()) {
                String name = propertyValue.getName();
                Object value = propertyValue.getValue();

                if (value instanceof BeanReference){
                    BeanReference beanReference =(BeanReference)value;
                    value = getBean(beanReference.getBeanName());
                }

                //填充属性
                BeanUtil.setFieldValue(bean,name,value);
            }
        }catch (Exception e){
            throw new BeansException("Error settiong property values: "+beanName);
        }

    }

    protected Object createBeanInstance(BeanDefinition beanDefinition, String beanName, Object[] args) {
        Constructor constructorToUse = null;
        Class<?> beanClass = beanDefinition.getBeanClass();
        //获取所有构造方法，数组形式，遍历参数个数一致的构造方法 TODO 未校验参数类型
        Constructor<?>[] declaredConstructors = beanClass.getDeclaredConstructors();
        for (Constructor ctor : declaredConstructors) {
            if (null != args && ctor.getParameterTypes().length == args.length) {
                constructorToUse = ctor;
                break;
            }
        }
        return instantiationStrategy.instantiate(beanDefinition, beanName, constructorToUse, args);
    }

}
